/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package chat;

import chat.server.model.DbHelper;
import chat.server.model.User;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mingq
 */
public class ServerClient extends Thread {

    private static final int PORT = 8081;
    private static final String SERVER = "localhost";
    private Socket serverSock;
    private DataInputStream reader;
    private DataOutputStream writer;
    private ChatMain mChatView;

    public ServerClient(ChatMain chatView) {
        mChatView = chatView;
    }

    private void initServerSocket(String server, int port) {
        try {
            serverSock = new Socket(server, port);
            InputStream in = serverSock.getInputStream();
            reader = new DataInputStream(in);
            OutputStream out = serverSock.getOutputStream();
            writer = new DataOutputStream(out);
        } catch (UnknownHostException ex) {
            LogManager.getLogger(ChatMain.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            LogManager.getLogger(ChatMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void login(String username, String password) {
        try {
            writer.write(Consts.LOGIN);
            writer.writeUTF(username);
            writer.writeUTF(password);
            writer.writeUTF(NetTools.getIP() + "#" + ClientServer.getPort());
        } catch (IOException ex) {
            LogManager.getLogger(ServerClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void echo(String str) {
        System.out.println("In Client Thread echo: " + str);
    }

    public void connectUser(String uid) {
        try {
            writer.write(Consts.GET_IP);
            writer.writeUTF(uid);
        } catch (IOException ex) {
            LogManager.getLogger(ChatMain.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void registerUser(String uid, String password, String nick) {
        try {
            writer.write(Consts.REGISTER);
            writer.writeUTF(uid);
            writer.writeUTF(password);
            writer.writeUTF(nick);
        } catch (IOException ex) {
            Logger.getLogger(ServerClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void changePassword(String uid, String password) {
        try {
            writer.write(Consts.CHANGE_PASSWORD);
            writer.writeUTF(uid);
            writer.writeUTF(password);
        } catch (IOException ex) {
            Logger.getLogger(ServerClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void changeNick(String uid, String nick) {
        try {
            writer.write(Consts.CHANGE_NICK);
            writer.writeUTF(uid);
            writer.writeUTF(nick);
        } catch (IOException ex) {
            Logger.getLogger(ServerClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void addFriend(String uid1, String uid2) {
        try {
            writer.write(Consts.ADD_FRIEND);
            writer.writeUTF(uid1);
            writer.writeUTF(uid2);
        } catch (IOException ex) {
            Logger.getLogger(ServerClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void addFriendComplete(String uid1, String uid2) {
        try {
            writer.write(Consts.ADD_FRIEND_COMPLETE);
            writer.writeUTF(uid1);
            writer.writeUTF(uid2);
        } catch (IOException ex) {
            Logger.getLogger(ServerClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void getAllUserNotFriend(String uid) {
        try {
            writer.write(Consts.GET_ALL_USER_NOT_FRIENDS);
            writer.writeUTF(uid);
        } catch (IOException ex) {
            Logger.getLogger(ServerClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    @Override
    public void run() {
        try {
            if (serverSock == null) {
                initServerSocket(SERVER, PORT);
            }
            int msg = -1;
            while ((msg = reader.read()) != -1) {
                switch (msg) {
                    case Consts.LOGIN_SUCCESS: {
                        String nick = reader.readUTF();
                        String strFriends = reader.readUTF();
                        mChatView.logined(true, nick, strFriends);
                        break;
                    }
                    case Consts.LOGIN_FAILED:
                        mChatView.logined(false, null, null);
                        break;
                    case Consts.GET_IP_SUCCESS:
                        String uip = reader.readUTF();
                        mChatView.connectUsered(uip);
                        break;
                    case Consts.ME_ONLINE: {
                        String uid = reader.readUTF();
                        mChatView.userOnline(uid);
                        break;
                    }
                    case Consts.ME_OFFLINE: {
                        String uid = reader.readUTF();
                        mChatView.userOffline(uid);
                        break;
                    }
                    case Consts.REGISTER_SUCCESS: {
                        mChatView.registered(true);
                        break;
                    }
                    case Consts.ADD_FRIEND_SUCCESS: {
                        mChatView.addFrineded(true);
                        break;
                    }
                    case Consts.ADD_FRIEND_COMPLETE_SUCCESS: {
                        mChatView.addFriendComPlete(true);
                        break;
                    }
                    case Consts.GET_ALL_USER_NOT_FRIENDS_SUCCESS: {
                        String strUsers = reader.readUTF();
                        mChatView.getAllUserNotFriended(strUsers);
                        break;
                    }
                    case Consts.FRIEND_REQUEST: {
                        String uid = reader.readUTF();
                        User user = DbHelper.getInstance().getUserByUid(uid);
                        user.online = true;
                        mChatView.friendRequest(user);
                        break;
                    }
                    default:
                        break;
                }
            }
        } catch (SQLException ex) {
            Logger.getLogger(ServerClient.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
